package com.limi.akka.scheduler;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Cancellable;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

/**
 * @author Limi Pan
 * @create 2018-09-17 11:15
 */
public class SchedulerTest {

    public static ActorSystem system;
    public static ActorRef worker;

    @BeforeClass
    public static void beforeClass(){
        system = ActorSystem.create("iot");
        worker = system.actorOf(WorkerActor.props(), "worker");
    }

    @Test
    public void test1() throws InterruptedException {
//        System.out.println("start time:" + getNowTime());

        for(int i=0;i<10000;i++){
            // 每50毫秒执行
            system.scheduler().scheduleOnce(Duration.ofMillis(1+i),
                    system.actorOf(WorkerActor.props(), "workerTest"+i),
                    "hello", system.dispatcher(), ActorRef.noSender());
        }

//        Thread.sleep(2000);

    }

    @Test
    public void test2() throws InterruptedException {
        // 2秒后执行一次
        system.scheduler().scheduleOnce(Duration.ofMillis(2000),
                new Runnable() {
                    @Override
                    public void run() {
                        worker.tell(getNowTime(), ActorRef.noSender());
                    }
                }, system.dispatcher());

        Thread.sleep(2000);

    }

    @Test
    public void test3() throws InterruptedException {
        /*
         * 0秒后每隔50耗秒
         */
        Cancellable cancellable = system.scheduler().schedule(Duration.ZERO,
                Duration.ofMillis(50), worker, "tick", system.dispatcher(), ActorRef.noSender());

        Thread.sleep(1000);

        //取消执行
//        cancellable.cancel();
//        Thread.sleep(1000);
    }

    @Test
    public void test4() throws InterruptedException {
        System.out.println(getNowTime());
        //如果传入schedule函数的第一个参数为0 seconds，则表示消息会及时发送，然后每隔5秒钟再重复发送。
//        system.scheduler().schedule(Duration.ZERO, Duration.ofSeconds(2), worker, "scheduler",
//                system.dispatcher(), ActorRef.noSender());
        // 5秒后每隔2秒执行一次
        system.scheduler().schedule(Duration.ofSeconds(5), Duration.ofSeconds(2), worker, "scheduler",
                system.dispatcher(), ActorRef.noSender());
        Thread.sleep(1000*10);

    }

    public static String getNowTime(){
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS").format(new Date());
    }
}
